<?php

namespace App\Http\Requests\Api;
use App\Models\Goods;
use App\Models\CouponsConfig;
use App\Models\Coupon;
class CouponsRequest extends FormRequest
{


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method()){
            case "POST":{
                return [
                    "goods_id"=>[
                        "required",
                        function($attribute,$value,$fail){
                            //是否在售
                            if (!$goods = Goods::find($value)){
                                abort(412,"商品不存在");
//                        return $fail("");
                            }
                            if (!$goods->on_sale||$goods->integral<=0){
                                abort(412,"商品已下架");
//                        return $fail("商品已下架");
                            }
                            if($goods->is_seckill){
                                abort(412,"秒杀产品，请至秒杀专栏下单");
//                        return $fail("秒杀产品，请至秒杀专栏下单");
                            }
                            //这人积分量是否足够购买这个产品的
                            if ($this->user()->userIntegral->integral<$goods->integral){
                                abort(412,"积分不足");
//                        return $fail("积分不足");
                            }
                            //是否限购
                            //限购的话这人通过积分买的数量是否超标
                            if ($goods->limit_number>0){
                                $count = $this->user()->coupons()->where("goods_id",$goods->id)
                                    ->where("type",CouponsConfig::COUPONS_TYPE_SHOP)->count();
                                if ($count>=$goods->limit_number){
                                    abort(412,"此商品限购");
//                            return $fail("此商品限购");
                                }
                            }
                        }
                    ]
                ];
            }
//            case "PATCH":{
////                dd($this->all());
//                return [
//                    "id"=>['required',
//                            function($attribute,$value,$fail){
//                                //是否在售
//                                if (!$coupon = Coupon::find($value)){
//                                    abort(412,"卡券不存在");
//                                }
//                                if ($coupon->is_used){
//                                    abort(412,"卡券已使用");
//                                }
//                                if ($coupon->is_passed){
//                                    abort(412,"卡券已过期");
//                                }
//                            }
//                        ],
//                ];
//            }
        }

    }
}
